<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>节点操作</title>
</head>
<body>
<button onclick="funA()">获取父节点</button>
<button onclick="funB()">获取子节点</button>
<button onclick="funC()">获取相邻节点</button>
<button onclick="funD()">添加子节点</button>
<button onclick="funE()">删除子节点</button>
<button onclick="funE2()">删除子节点</button>
<hr/>
<div id="d1">
    <div id="d2">
        <span>div2中的span1</span>
        <label>div2中的label</label>
        <span id="s22">div2中的span2</span>
        <span>div2中的span3</span>
        <span id="s24">div2中的span4</span>
    </div>
    <span id="s1">div1中的span</span>
    <div id="d3">
        <span>div3中的span</span>
    </div>
    <div id="d4">
        <span>div4中的span</span>
    </div>
    <div id="d5">
        <p>段落1</p>
        <p id="p2">段落2</p>
        <p>段落3</p>
        <p>段落4</p>
        <p>段落5</p>
        <p>段落6</p>
    </div>
</div>
</body>
</html>
<script>
    function funA() {
        let s1Obj = document.getElementById('s1');
        let d1Obj = s1Obj.parentElement;
        d1Obj.style.backgroundColor = "red";
    }

    let colorArray = ["#ceefab", "#abcdef", "#df1d1d", "#1434ab"]

    function funB() {
        let d2Obj = document.getElementById('d2');
        let children1 = d2Obj.children
        console.log(children1.length);
        for (e of children1) {
            e.style.backgroundColor = colorArray[Math.floor(Math.random() * 4)];
        }
    }

    function funC() {
        let s2Obj = document.getElementById('s24');
        let nextElement = s2Obj.nextElementSibling
        let prevElement = s2Obj.previousElementSibling
        console.log(nextElement);
        console.log(prevElement);
    }

    function funD() {
        let d3Obj = document.getElementById('d3');
        // 定义一个节点
        let createElement = document.createElement('span');
        // 给节点添加文本
        createElement.innerText = '我是添加的';
        // 添加到了d3Obj中
        d3Obj.appendChild(createElement);
        // d3Obj.appendChild('<span>abcd我是添加的</span>') ❌
        // d3Obj.innerHTML = '<span>abcd我是添加的</span>' 不合适
    }

    function funE() {
        let d5Obj = document.getElementById('d5');
        let p2Obj = document.getElementById('p2');
        d5Obj.removeChild(p2Obj);
    }

    function funE2() {
        let d5Obj = document.getElementById('d5');
        let childrens = d5Obj.children
        // 错误的写法
        /*for (let i = 0; i < childrens.length; i++) {
            d5Obj.removeChild(childrens[i]);

        }
        for (e of childrens) {
            d5Obj.removeChild(e)
        }
        */
        // 正确的写法
        for (let i = childrens.length - 1; i >= 0; i--) {
            d5Obj.removeChild(childrens[i]);
        }
    }
</script>
<!--节点：元素节点、属性节点、文本节点、空节点、注释节点-->